<template>
  <Layout style="height: 100%" class="main">
    <Header class="header-con" style="height: 54px; line-height: 54px">
      <div style="height: 54px">
        <img
          src="../../assets/images/shuhua_new.png"
          style="margin-left: 0px; width: 95px; height: 34px; margin-top: 10px"
        />
        <div class="divSplit"></div>
        <div style="display: inline-block">
          <div class="div_title" style="float: left">{{ logoTitle }}</div>
        </div>

        <div class="div_func">
          <div
            style="
              display: inline-block;
              float: left;
              color: #ffffff;
              font-size: 16px;
            "
          >
            <Icon
              type="md-person"
              size="18"
              color="#1D1E23"
              style="
                background: #fff;
                margin-left: 5px;
                margin-top: 5px;
                margin-right: 2px;
              "
            />
            <span>{{$t('welcome')}},</span
            ><span class="userName" @click="showPersonalModal">{{
              userName
            }}</span>
          </div>

          <div style="margin-top: 10px; display: inline-block">
            <div
              :title="$t('warn')"
              class="btn iconwrap"
              @click="handleGo"
              style="margin-left: 0px"
            >
              <img style="width: 40px" src="../../assets/images/notice_.png" />
              <span v-if="warnList.length &&  +roleId !==1" class="warningicon"></span>
            </div>
            <div :title="$t('set')" class="btn" @click="pwdModalVisiable = true">
              <img style="width: 40px" src="../../assets/images/set up_.png" />
            </div>
            <div :title="$t('exit')" class="btn" @click="logout">
              <img style="width: 40px" src="../../assets/images/exit_.png" />
            </div>
          </div>
        </div>
      </div>
    </Header>
    <Layout style="height: auto; overflow-y: auto">
      <Sider
        hide-trigger
        collapsible
        :width="220"
        :collapsed-width="64"
        v-model="collapsed"
        class="left-sider"
        :style="{ overflow: 'hidden' }"
      >
        <side-menu
          accordion
          ref="sideMenu"
          :active-name="$route.name"
          :collapsed="collapsed"
          @on-select="turnToPage"
          :menu-list="menuList"
        >
        </side-menu>
      </Sider>
      <Layout>
        <Content
          class="main-content-con"
          style="height: auto; overflow-y: auto"
          id="right_main"
        >
          <div
            style="
              margin-top: 10px;
              border-bottom: 1px solid #eee;
              padding-bottom: 10px;
            "
          >
            <sider-trigger
              :collapsed="collapsed"
              icon="md-menu"
              @on-change="handleCollapsedChange"
            ></sider-trigger>
            <custom-bread-crumb
              show-icon
              style="margin-left: 15px"
              :list="breadCrumbList"
            ></custom-bread-crumb>
          </div>
          <Layout class="main-layout-con" style="height: auto; margin: 20px">
            <keep-alive :include="cacheList">
              <router-view />
            </keep-alive>
          </Layout>
          <Modal
            v-model="personalModalVisiable"
            width="500"
            :title="$t('loginL.editInfoPer')"
            :mask-closable="false"
          >
            <Form
              ref="personalFormRef"
              :model="personalForm"
              :rules="personFormRules"
              :label-width="120"
            >
            <FormItem :label="$t('common.mail')" prop="mail" v-show="$i18n.locale === 'en-US'">
                <Input
                  v-model="personalForm.mail"
                  disabled
                  :placeholder="$t('common.emailPlaceTips')"
                ></Input>
              </FormItem>
              <FormItem :label="$t('common.phone')" prop="phone" v-show="$i18n.locale === 'zh-CN'">
                <Input
                  v-model="personalForm.phone"
                  disabled
                  :placeholder="$t('common.phonePlaceTips')"
                ></Input>
              </FormItem>
            
              <FormItem :label="$t('common.name')" prop="nickName">
                <Input
                  v-model="personalForm.nickName"
                  :placeholder="$t('common.newNamePlaceTips')"
                ></Input>
              </FormItem>
              <!--              <FormItem label="密码" prop="confirmPwd">-->
              <!--                <Input v-model="personalForm.password" placeholder="请输入当前密码以验证您的身份" type="password"></Input>-->
              <!--              </FormItem>-->
            </Form>
            <div slot="footer" style="text-align: center">
              <Button @click="personalModalVisiable = false">{{$t('cancel')}}</Button>
              <Button
                type="primary"
                @click="updatePersonal"
                :loading="personalLoading"
                style="margin-left: 15px"
              >
                <span v-if="!personalLoading">{{$t('save')}}</span>
                <span v-else>{{$t('save')}}....</span>
              </Button>
            </div>
          </Modal>
          <Modal
            v-model="pwdModalVisiable"
            width="500"
            :title="$t('loginL.editPasswordTitle')"
            :mask-closable="false"
          >
            <Form
              ref="pwdForm"
              :model="pwdForm"
              :rules="pwdFormRules"
              :label-width="120"
            >
              <FormItem :label="$t('loginL.oldPwd')" prop="oldPwd">
                <Input
                  v-model="pwdForm.oldPwd"
                  :placeholder="$t('loginL.pwdOldPlaceTips')"
                  type="password"
                ></Input>
              </FormItem>
              <FormItem :label="$t('loginL.pwd')" prop="pwd">
                <Input
                  v-model="pwdForm.pwd"
                  :placeholder="$t('loginL.pwdNewPlaceTips')"
                  type="password"
                ></Input>
              </FormItem>
              <FormItem :label="$t('loginL.confirmPwd')" prop="confirmPwd">
                <Input
                  v-model="pwdForm.confirmPwd"
                  :placeholder="$t('loginL.pwdConfirmPlaceTips')"
                  type="password"
                ></Input>
              </FormItem>
            </Form>
            <div slot="footer" style="text-align: center">
              <Button @click="pwdModalVisiable = false">{{$t('cancel')}}</Button>
              <Button
                type="primary"
                @click="changePwd"
                :loading="pwdLoading"
                style="margin-left: 15px"
              >
                <span v-if="!pwdLoading">{{$t('save')}}</span>
                <span v-else>{{$t('save')}}....</span>
              </Button>
            </div>
          </Modal>
        </Content>
      </Layout>
    </Layout>
  </Layout>
</template>
<script>
import applyApi from "@/api/applyApi";
import UserApi from "@/api/userApi";
import TrainCenterApi from "@/api/trainCenterApi";
import SideMenu from "./components/side-menu";
import HeaderBar from "./components/header-bar";
import TagsNav from "./components/tags-nav";
import User from "./components/user";
import ABackTop from "./components/a-back-top";
import Fullscreen from "./components/fullscreen";
import Language from "./components/language";
import ErrorStore from "./components/error-store";
import { mapMutations, mapActions, mapGetters } from "vuex";
import { getNewTagList, routeEqual } from "@/libs/util";
import routers from "@/router/routers";
import minLogo from "@/assets/images/logo-min.jpg";
import maxLogo from "@/assets/images/logo.jpg";
import siderTrigger from "./components/header-bar/sider-trigger";
import customBreadCrumb from "./components/header-bar/custom-bread-crumb";
import "./main.less";

export default {
  name: "Main",
  components: {
    SideMenu,
    HeaderBar,
    Language,
    TagsNav,
    Fullscreen,
    ErrorStore,
    User,
    ABackTop,
    siderTrigger,
    customBreadCrumb,
  },
  data() {
    const validateChangePassCheck = (rule, value, callback) => {
      if (value !== this.pwdForm.pwd) {
      
        callback(new Error(this.$t('common.pwd2Diff')));
      } else {
        callback();
      }
    };
    return {
      roleId:0,
      warnList: [],
      logoTitle: "",
      personalLoading: false,
      personalModalVisiable: false,
      pwdLoading: false,
      collapsed: false,
      minLogo,
      maxLogo,
      isFullscreen: false,
      userName: "",
      pwdModalVisiable: false,
      personalForm: {
        phone: "",
        nickName: "",
        password: "",
        mail:''
      },
      pwdForm: {
        oldPwd: "",
        pwd: "",
        confirmPwd: "",
      },
      personFormRules: {
        phone: [
          { required: true, message: this.$t('common.phoneMustTips'), trigger: "blur" },
          {
            type: "string",
            pattern: "^[1][3-9][0-9]{9}$",
            message: this.$t('common.phoneFormate'), 
            trigger: "blur",
          },
        ],
        nickName: [
          { required: true, message:this.$t('common.nameMustTips'),  trigger: "blur" },
          { type: 'string', min: 2, max: 32, message: this.$t('common.name2and32'),  trigger: 'blur' }
          // {
          //   type: "string",
          //   pattern: "^[\u4E00-\u9FA5]{2,6}$",
          //   message: "姓名必须是长度必须2-6位的中文",
          //   trigger: "blur",
          // },
        ],
        password: [{ validator: validateChangePassCheck, trigger: "blur" }],
      },
      pwdFormRules: {
        oldPwd: [
          { required: true, message:this.$t('common.oldPwdMustTips'), trigger: "blur" },
        ],
        pwd: [
          { required: true, message:this.$t('common.passwordMustTips'),  trigger: "blur" },
          {
            type: "string",
            min: 6,
            max: 18,
            message:  this.$t('common.password6and8'),
            trigger: "blur",
          },
        ],
        confirmPwd: [
          { required: true, message:  this.$t('common.confirmPasswordMustTips '), trigger: "blur" },
          {
            type: "string",
            min: 6,
            max: 18,
            message:  this.$t('common.password6and8'),
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["errorCount"]),
    tagNavList() {
      return this.$store.state.app.tagNavList;
    },
    tagRouter() {
      return this.$store.state.app.tagRouter;
    },
    userAvator() {
      return this.$store.state.user.avatorImgPath;
    },
    cacheList() {
      const list = [
        "ParentView",
        ...(this.tagNavList.length
          ? this.tagNavList
              .filter((item) => !(item.meta && item.meta.notCache))
              .map((item) => item.name)
          : []),
      ];
      return list;
    },
    menuList() {
      console.log("menuList:" + JSON.stringify(this.$store.getters.menuList));
      return this.$store.getters.menuList;
    },
    local() {
      return this.$store.state.app.local;
    },
    hasReadErrorPage() {
      return this.$store.state.app.hasReadErrorPage;
    },
    unreadCount() {
      return this.$store.state.user.unreadCount;
    },
    breadCrumbList() {
      return this.$store.state.app.breadCrumbList;
    },
  },
  methods: {
    ...mapGetters(["getPhone", "getNickName", "getRoleId","getMail"]),
    ...mapMutations([
      "setBreadCrumb",
      "setTagNavList",
      "addTag",
      "setHomeRoute",
      "closeTag",
      "setNickName",
      "setLocal"
    ]),
    ...mapActions(["handleLogin", "handleLogOut"]),
    showPersonalModal() {
      this.$refs.personalFormRef.resetFields();
      this.personalForm = {
        phone: this.getPhone(),
        nickName: this.getNickName(),
        mail:this.getMail()
      };
      this.personalModalVisiable = true;
    },
    getWarnList() {
      applyApi.message({pageSize:10,currentPage:1}).then((res) => {
        
        this.warnList = res.data.data.list.items;
      });
    },
    updatePersonal() {
      this.$refs.personalFormRef.validate((valid) => {
        if (valid) {
          this.personalLoading = true;
          UserApi.updatePersonalInfo(this.personalForm).then(
            (response) => {
              this.personalLoading = false;
              this.$Message.success(this.$t('common.editSuc'));

              // 更新昵称
              this.setNickName(this.personalForm.nickName);
              this.showUserName();
              this.$refs.personalFormRef.resetFields();
              this.personalModalVisiable = false;
            },
            (error) => {
              this.personalLoading = false;
              this.$Message.error(error.response.data.msg);
            }
          );
        }
      });
    },
    changePwd() {
      this.$refs.pwdForm.validate((valid) => {
        if (valid) {
          this.pwdLoading = true;
          UserApi.changeSelfPwd(
            this.pwdForm.oldPwd,
            this.pwdForm.pwd,
            this.pwdForm.confirmPwd
          ).then(
            (response) => {
              this.pwdLoading = false;
              this.$Message.success(this.$t('common.editSuc'));
              this.$refs.pwdForm.resetFields();
              this.pwdModalVisiable = false;
            },
            (error) => {
              this.pwdLoading = false;
              this.$Message.error(error.response.data.msg);
            }
          );
        }
      });
    },
    logout() {
      this.handleLogOut().then(() => {
        this.$router.push({
          name: "login",
        });
      });
    },
    turnToPage(route) {
      let { name, params, query } = {};
      if (typeof route === "string") name = route;
      else {
        name = route.name;
        params = route.params;
        query = route.query;
      }
      if (name.indexOf("isTurnByHref_") > -1) {
        window.open(name.split("_")[1]);
        return;
      }
      this.$router.push({
        name,
        params,
        query,
      });
    },
    handleCollapsedChange(state) {
      this.collapsed = state;
    },
    handleCloseTag(res, type, route) {
      if (type !== "others") {
        if (type === "all") {
          this.turnToPage(this.$config.homeName);
        } else {
          if (routeEqual(this.$route, route)) {
            this.closeTag(route);
          }
        }
      }
      this.setTagNavList(res);
    },
    handleClick(item) {
      this.turnToPage(item);
    },
    showUserName() {
      this.userName = this.getNickName();
    debugger
      if (+this.roleId == 1) {
        this.userName = this.userName + "("+ this.$t("loginL.sysOpt") +")";
      } else if (+this.roleId == 4) {
        this.userName = this.userName + "("+this.$t("cocach")+")";
      }
    },
    handleGo() {
      this.$router.push({
        name: "warn",
      });
    },
  },
  watch: {
    $route(newRoute) {
      const { name, query, params, meta } = newRoute;
      this.addTag({
        route: { name, query, params, meta },
        type: "push",
      });
      this.setBreadCrumb(newRoute);
      this.setTagNavList(getNewTagList(this.tagNavList, newRoute));
      this.$refs.sideMenu.updateOpenName(newRoute.name);
    },
  },
  created(){
    this.roleId = this.getRoleId();

  },
  mounted() {
    debugger
    /**
     * @description 初始化设置面包屑导航和标签导航
     */
    this.getWarnList();
    this.setTagNavList();
    this.setHomeRoute(routers);
    const { name, params, query, meta } = this.$route;
    this.addTag({
      route: { name, params, query, meta },
    });
    this.setBreadCrumb(this.$route);

    // 设置初始语言
       this.setLocal(this.$i18n.locale)
    // 如果当前打开页面不在标签栏中，跳到homeName页
    if (!this.tagNavList.find((item) => item.name === this.$route.name)) {
      this.$router.push({
        name: this.$config.homeName,
      });
    }
    
    this.showUserName();
    // logoTitle
    // 如果是训练中心管理员，这边则展示训练中心名称
    
    if (+this.roleId == 2 || +this.roleId == 3) {
      TrainCenterApi.getUserTrainCenterNames().then(
        (response) => {
          this.logoTitle = response.data.data.name;
        },
        (error) => {
          this.$Message.error(error.response.data.msg);
        }
      );
    } else {
      this.logoTitle = this.$t('loginL.sysNameLogo')
    }
  },
};
</script>
<style lang="less">
@import "../../theme/mycolor.less";
.divSplit {
  width: 1px;
  height: 14px;
  background: @logo-color;
  margin-left: 14px;
  margin-right: 14px;
  display: inline-block;
  margin-bottom: 10px;
}

.div_title {
  height: 16px;
  line-height: 16px;
  display: inline-block;
  margin-left: 0px;
  color: @logo-color;
  font-size: 18px;
  font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB,
    Microsoft YaHei, "\5FAE\8F6F\96C5\9ED1", Arial, sans-serif;
  font-weight: 500;
  margin-bottom: 10px;
}

.div_func {
  display: inline-block;
  float: right;
  margin-right: 5px;
}

.div_func .btn {
  cursor: pointer;
  display: inline-block;
  width: 28px;
  height: 28px;
  border-radius: 14px;
  margin-left: 10px;
  opacity: 0.8;
}

.div_func .btn:hover,
.div_func .btn:active {
  opacity: 0.4;
}

span.userName {
  cursor: pointer;
  text-decoration: underline;
}

span.userName:hover {
  text-decoration: underline;
  color: #aaa;
}
.iconwrap {
  position: relative;
  .warningicon {
    position: absolute;
    right: -10px;
    top: 0;
    height: 10px;
    width: 10px;
    border-radius: 50%;
    background-color: red;
  }
}
</style>
